// This is the main entry point of the home page.
// The ready method should be invoked by the ready
// event of the home page.
function HomeController(){
	// When a function is used as a constructor, its "this" is set to the new object.
	// the following creates a member ( instance ) variable.
	this.orgsController = new OrgsController();
	this.personsController = new PersonsController();
	
	// For use in closures and callbacks where this keyword points to something else.
	var homeControllerThis = this; 
	
	if(typeof HomeController.prototype.ready == "undefined"){
		// assume all functions need to be added to the prototype
		
		HomeController.prototype.ready = function() {
			// This is not a callback function.
			// It is invoked as an object method, so "this" points to the home instance.
			
			// Handle the case where the browser doesn't support the console...
		    // Not 100% sure this is necessary as we are targeting modern browsers.
			if (!window.console){
				console = {};
			}
			console.log = console.log || function(){};
			console.warn = console.warn || function(){};
			console.error = console.error || function(){};
			console.info = console.info || function(){};
			
		    // Set up history and bookmark handling.
		    // This code is mostly from: https://github.com/balupton/history.js
		    if ( document.location.protocol === 'file:' ) {
		    	alert('The HTML5 History API (and thus History.js) do not work on files, please upload it to a server.');
		    }
		    // The window.History is put into the global scope by History.js
		    //console.log('initial history state: ', JSON.stringify(History.getState()));
		    // Hook up the history change handler... this is the major driver of app behavior.
		    History.Adapter.bind(window,'statechange', this.stateChangeHandler);

			$( "#dialog-modal" ).dialog({
				height: 140,
				autoOpen: false,
				modal: true,
				resizable: false
			});
			$(".ui-dialog-titlebar").hide();

			
		    // Get the context to load the page header and for types and roles.
		    // !!!! Global !!!!!!!!
		    // Why?
		    
		    contextController = new ContextController(this);
		    var promise = contextController.get();
	        $.when(promise).then(this.stateChangeHandler);
		}
		HomeController.prototype.stateChangeHandler = function (){
			// This function is invoked directly, in the ready method above,
			// and as a callback.
			// When invoked directly, "this" == the promise object.
			// When invoked as a callback, "this" == the window object, I think.
			
		     //console.log('statechangeHandler... JSON.stringify(State): ' + JSON.stringify(History.getState()));
		     $('.fap_menu_clickable_class').removeClass("fap_menu_active_class");
		     switch ( History.getState().data.tab ){ // tab level switch
		  	 case "admin":
		  		 switch( History.getState().data.subTab){ // subTab switch
		   		 case "orgs":
		   			 $("#menu_item_orgs_id").addClass("fap_menu_active_class");
		             var promise = homeControllerThis.orgsController.getWithNoId();
	    	         $.when(promise).then(function(){
	   	                 $("#org_name_id").focus();
	    	         });
		   			 break;
		         case "org":
		   			 $("#menu_item_orgs_id").addClass("fap_menu_active_class");
		   			 if($("#org_reset_button_id").is(":visible")){
		   				 // there is an unsaved change
		   				 $("#org_reset_button_id").click();
		   			 }
		   			 var promise = homeControllerThis.orgsController.getById(History.getState().data.id, 
		   					 History.getState().data.version,
		   					 History.getState().data.parentKeys);
	    	         $.when(promise).then(function(){
	   	                 $("#org_name_id").focus();
	    	         });
		   			 break;
		   		 case "persons":
		   			 $("#menu_item_persons_id").addClass("fap_menu_active_class");
		   			 homeControllerThis.personsController.get();
		   			 break;
		   		 case "person":
		   			 $("#menu_item_persons_id").addClass("fap_menu_active_class");
		             var personController = new PersonController();
		             personController.get(History.getState().data.id);
		   			 break;
		         case undefined : 
		        	 throw "history has tab but no subTab: " + JSON.stringify(History.getState());
		        	 break;
				 default : throw "unsupported value for subTab: " + History.getState().data.subTab;
		   		 }
		   	     break;
		   	  case undefined : 
		   	      // This triggers another state change, as the URL has changed
		   	      // Here is how bookmarked URLs work... if the exact URL is found in the browser history,
		   	      // then the data values are loaded. If not, they are empty.
		   		  //
		   		  // The URL contains enough information to reconstruct the state.
		   		  // Todo: get the information from the URL, so that ancient bookmarked
		   		  //       urls still work.
		          History.replaceState({"tab":"admin","subTab" : "orgs"},  $("#pageTitle").text() + "...Organizations", "?tab=admin&subTab=orgs");
		   	      break;
		   	  default : throw "unsupported value for tab: " + History.getState().data.tab;
		   	  }
		  }
		HomeController.prototype.getParentKeysForUrl = function(parentKeys){
			var parentsForUrl = "";
			$.each(parentKeys, function(index, parentKey) {
				 parentsForUrl = parentsForUrl + "&parentId=" + parentKey;
			});
			return parentsForUrl;
		}
		HomeController.prototype.orgClickHandler = function(id, title, version, parentIds){
	    	History.pushState({"tab":"admin",
	    						"subTab" : "org", 
	    						"id" : id,
	    						"version": version,
	    						"parentKeys" : parentIds},
	    						"Org Vault: " + title,
	    						"?tab=admin&subTab=org&id=" + id +
	    						"&version=" + version +
	    						homeControllerThis.getParentKeysForUrl(parentIds));
	    }
		HomeController.prototype.orgsClickHandler = function(){
			var now = new Date().getTime(); 
			// Put something unique in the URL so that it is recognized as a new one.
		    History.pushState({"tab":"admin","subTab" : "orgs"},
		    		$("#pageTitle").text() + "Org Vault...Organizations ", "?tab=admin&subTab=orgs&now=" + now);
		}
		HomeController.prototype.personClickHandler = function(id){
			console.log("personClickHandler");
			alert("not implemented yet!");
		    //History.pushState({"tab":"admin","subTab" : "person", "id" : id},  $("#pageTitle").text() + "...Person: " + id, "?tab=admin&subTab=person&id=" + id);
		}
		HomeController.prototype.personsClickHandler = function(){
			console.log("personsClickHandler");
			
            var now = new Date().getTime(); 
            // Put something unique in the URL so that it is recognized as a new one.
            History.pushState({"tab":"admin","subTab" : "persons"},
                    $("#pageTitle").text() + "Org Vault...People ", "?tab=admin&subTab=persons&now=" + now);
		}
		HomeController.prototype.personAddClickHandler = function(){
		    History.pushState({"tab":"admin","subTab" : "person"},  $("#pageTitle").text() + "...person add ", "?tab=admin&subTab=person");
		}
		HomeController.prototype.bootstrapClickHandler = function(){
		    History.pushState({"tab":"admin","subTab" : "bootstrap"},  $("#pageTitle").text() + "...bootstrap ", "?tab=admin&subTab=bootstrap");
		}
		HomeController.prototype.pageHelpClickHandler = function(){
		    console.log("pageHelpClickHandler");
		    
		}
	}
}

